#include "texture.h"
#include <GL/glew.h>
#include "stb_image.h"

namespace kanon
{
    Texture2D::Texture2D(float r, float g, float b)
    {
        unsigned char pixel_data[3];
        pixel_data[0] = static_cast<unsigned char>(r * 255);
        pixel_data[1] = static_cast<unsigned char>(g * 255);
        pixel_data[2] = static_cast<unsigned char>(b * 255);

        glGenTextures(1, &texture_id);
        glBindTexture(GL_TEXTURE_2D, texture_id);

        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);

        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 1, 1, 0, GL_RGB, GL_UNSIGNED_BYTE, pixel_data);
        glGenerateMipmap(GL_TEXTURE_2D);

        glBindTexture(GL_TEXTURE_2D, 0);

        this->width = 1;
        this->height = 1;
    }

    Texture2D::Texture2D(const std::string& texture_path)
    {
        glGenTextures(1, &texture_id);

        int width, height, nrChannels;
        stbi_set_flip_vertically_on_load(true);
        unsigned char* data = stbi_load(texture_path.c_str(), &width, &height, &nrChannels, 0);

        this->width = width;
        this->height = height;

        if (data) 
        {
            GLenum format = (nrChannels == 4) ? GL_RGBA : GL_RGB;

            glBindTexture(GL_TEXTURE_2D, texture_id);
            glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0,
                format, GL_UNSIGNED_BYTE, data);
            glGenerateMipmap(GL_TEXTURE_2D);

            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

            stbi_image_free(data);
            glBindTexture(GL_TEXTURE_2D, 0);
        }
        else 
        {
            glDeleteTextures(1, &texture_id);
            texture_id = 0;
        }
    }
}
